
"""\
The formatter supports the parsing of object library file.
"""

import time

__version__ = "1.10"

__aof__ = ('Library Decoder', 'LIB')
__extension__ = (('Library Files', ('*.lib', '*.a')),)


class _LibDecoder:
    def Execute(self, source, target, notify, **kws):

        def _spString(nb, data, **args):
            k = len(data) - 1
            while k >= 0:
                if ord(data[k]) != 0x20:
                    return data[:k+1]
                k -= 1

            return ''

        def _digit10(nb, data, **args):
            try:
                return int(_spString(nb, data, **args))
            except:
                return 0

        def _spDate(nb, data, **args):
            return time.ctime(_digit10(nb, data, **args))

        entry = target.getEntry()
        start = kws.get('start', 0)

        length = len(source)
        kws['offset'] = 0

        # Library Magic is !<arch>\012
        magic = target.readString(source, 8)
        if magic != '!<arch>\012':
            return False

        entry.append(
            target.newItemObject(
                'Magic', '!<arch>\012',
                field=target.newFieldObject(start, 8)))
        kws['offset'] = 8

        _HEADER = (
            ('Name', 16, 'string,export', {'function': _spString}),
            ('Date', 12, 'string', {'function': _spDate}),
            ('UID', 6, 'value', {'function': _digit10}),
            ('GID', 6, 'value', {'function': _digit10}),
            ('Mode', 8, 'value', {'function': _digit10}),
            ('Size', 10, 'decimal,export', {'function': _digit10}),
            ('Fmag', 2, 'value')
        )

        ret = True
        while ret and kws['offset'] < length:
            ret, obj, consumed, _, exported = target.parse('Header', _HEADER,
                                                           afile=source, **kws)
            if ret:
                try:
                    size = int(exported[1])
                except ValueError:
                    return False

                if size != 0:
                    offset = start + kws['offset']
                    objectp = target.newItemObject(
                        exported[0],
                        field=target.newFieldObject(offset, consumed + size))
                    objectp.appendChildren(obj)

                    objectp.appendChildren(
                        target.newItemObject(
                            'Data',
                            attribute='extractable',
                            field=target.newFieldObject(
                                offset + consumed, size)))
                    entry.append(objectp)

                kws['offset'] += consumed + size
                if kws['offset'] & 0x01:
                    kws['offset'] += 1

        return ret


def fmtService():
    return _LibDecoder
